package org.ytor.core.sysapi.file.logic;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.ytor.common.enums.MimeType;
import org.ytor.common.enums.RespCode;
import org.ytor.common.exception.BaseException;
import org.ytor.common.exception.DownloadException;
import org.ytor.common.util.Ios;
import org.ytor.common.util.Strs;
import org.ytor.core.sysapi.file.service.F;
import org.ytor.core.sqlflow.BaseLogic;
import org.ytor.core.sysapi.file.model.SysFile;
import org.ytor.core.sysapi.file.repository.SysFileRepository;
import org.ytor.core.util.RespUtil;

import java.io.IOException;
import java.io.InputStream;

/**
 * created by yangtong on 2025/4/11 22:44:42
 */
@Service
public class SysFileLogic extends BaseLogic<SysFile, SysFileRepository> {

    public void delete(String fileId) {
        if (Strs.isEmpty(fileId)) {
            return;
        }
        SysFile sysFile = repository.queryById(fileId);
        if (sysFile != null) {
            F.remove(fileId);
            repository.deleteById(sysFile.getId());
        }
    }

    public String upload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        long fileSize = file.getSize();
        String fileSizeText = Strs.formatSize(fileSize);
        String fileType = file.getContentType();
        try (InputStream is = file.getInputStream()) {
            //上传文件
            String fileId = F.upload(is);
            //保持文件上传记录
            SysFile sysFile = new SysFile();
            sysFile.setFileId(fileId);
            sysFile.setFileName(fileName);
            sysFile.setFileSize(fileSize);
            sysFile.setFileSizeText(fileSizeText);
            sysFile.setFileType(fileType);
            sysFile.setDownloadCount(0);
            repository.insert(sysFile);

            return fileId;
        } catch (IOException e) {
            throw new BaseException(e);
        }
    }

    public void download(String fileId) {
        SysFile sysFile = repository.queryOne(w -> w.eq(SysFile::getFileId, fileId));
        if (sysFile == null) {
            throw new DownloadException(RespCode.FILE_NOT_FOUND);
        }
        //获取文件流
        try (InputStream inputStream = F.get(fileId)) {
            HttpServletResponse resp = RespUtil.getResp();

            //设置响应头
            RespUtil.downloadResponse(sysFile.getFileName(), MimeType.get(sysFile.getFileType()));
            resp.setContentLengthLong(sysFile.getFileSize());
            Ios.copy(inputStream, resp.getOutputStream());

            //刷新
            resp.flushBuffer();

            repository.update().set(SysFile::getDownloadCount, sysFile.getDownloadCount() + 1)
                    .where(w -> w.eq(SysFile::getId, sysFile.getId()));
        } catch (IOException e) {
            throw new BaseException(e);
        }
    }
}
